//
//  ZCOutboundPlanViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/5.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCOutboundPlanViewController.h"
#import "ZCTaskTitleView.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCPutInStorageTableViewCell.h"
#import "ZCOutboundPlanModel.h"
#import "ZCOutboundPlanDetailViewController.h"

static NSString *totalNumCellID = @"ZCTaskTotalNumTableViewCell";
static NSString *storageCellID = @"ZCPutInStorageTableViewCell";

@interface ZCOutboundPlanViewController ()<ZCTaskTitleViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) ZCTaskTitleView *taskTitleView;
@property (nonatomic, copy) NSString *currentStatus;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) ZCOutboundPlanModel *obPlanModel;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCOutboundPlanViewController
#pragma mark - 懒加载
- (ZCTaskTitleView *)taskTitleView {
    if (!_taskTitleView) {
        _taskTitleView = [[ZCTaskTitleView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, space(80))];
        _taskTitleView.delegate = self;
    }
    return _taskTitleView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, space(80) + 64, SCREENWIDTH, SCREENHEIGHT - space(80) - 64) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:totalNumCellID];
        [_tableView registerClass:[ZCPutInStorageTableViewCell class] forCellReuseIdentifier:storageCellID];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationItem.title = @"出库计划";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.taskTitleView];
    self.taskTitleView.titleArray = @[@"未出库",@"已出库"];
    self.currentStatus = @"10";
    [self.view addSubview:self.tableView];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self.hud showAnimated:YES];
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)loadData {
    self.currentPage = 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
    [param setObject:houseId forKey:@"houseId"];
    [param setObject:self.currentStatus forKey:@"status"];
    [param setObject:@(self.currentPage) forKey:@"current"];
    [param setObject:@(10) forKey:@"size"];
    
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:OutboundPlanList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                [weakSelf.listArray removeAllObjects];
                weakSelf.obPlanModel = [ZCOutboundPlanModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.listArray addObjectsFromArray:weakSelf.obPlanModel.records];
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_header endRefreshing];
                if (weakSelf.listArray.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud showAnimated:YES];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                });
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
        }];
    });
}

- (void)loadMoreData {
    self.currentPage++;
    if (self.currentPage <= [self.obPlanModel.pages integerValue]) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        NSString *houseId = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreId];
        [param setObject:houseId forKey:@"houseId"];
        [param setObject:self.currentStatus forKey:@"status"];
        [param setObject:@(self.currentPage) forKey:@"current"];
        [param setObject:@(10) forKey:@"size"];
        
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:OutboundPlanList params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    weakSelf.obPlanModel = [ZCOutboundPlanModel yy_modelWithDictionary:responseObject[@"data"]];
                    [weakSelf.listArray addObjectsFromArray:weakSelf.obPlanModel.records];
                    [weakSelf.tableView reloadData];
                    if (weakSelf.listArray.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud showAnimated:YES];
                        weakSelf.hud.mode = MBProgressHUDModeText;
                        weakSelf.hud.label.text = responseObject[@"message"];
                        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                    });
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                [weakSelf.tableView.mj_footer endRefreshing];
            }];
        });
    }else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
}

#pragma mark - ZCTaskTitleViewDelegate
- (void)taskTitleViewButttonWithTitle:(NSString *)title {
    if ([title isEqualToString:@"未出库"]) {
        if ([self.currentStatus integerValue] != 10) {
            self.currentStatus = @"10";
            [self.hud showAnimated:YES];
            [self loadData];
        }
    }else if ([title isEqualToString:@"已出库"]) {
        if ([self.currentStatus integerValue] != 30) {
            self.currentStatus = @"30";
            [self.hud showAnimated:YES];
            [self loadData];
        }
    }
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZCTaskTotalNumTableViewCell *numCell = [tableView dequeueReusableCellWithIdentifier:totalNumCellID forIndexPath:indexPath];
        numCell.selectionStyle = UITableViewCellSelectionStyleNone;
        numCell.title = @"任务总数";
        numCell.content = self.obPlanModel.total;
        return numCell;
    }else {
        ZCPutInStorageTableViewCell *storageCell = [tableView dequeueReusableCellWithIdentifier:storageCellID forIndexPath:indexPath];
        storageCell.selectionStyle = UITableViewCellSelectionStyleNone;
        storageCell.typeTitle = @"车型";
        storageCell.statusTitle = @"状态";
        ZCOutboundPlanInfoModel *obPlanM = self.listArray[indexPath.section - 1];
        storageCell.obPlanModel = obPlanM;
        
        return storageCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return space(90);
    }else {
        return space(360);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


#pragma mark - UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCOutboundPlanDetailViewController *detailVC = [[ZCOutboundPlanDetailViewController alloc] init];
    ZCOutboundPlanInfoModel *infoModel = self.listArray[indexPath.section - 1];
    detailVC.houseId = self.obPlanModel.condition.houseId;
    detailVC.key = infoModel.noticeLineId;
    detailVC.visitType = @"CLICK";
    detailVC.fromPlan = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
